#pragma once


#include <stdint.h>

#include "between_face_common.hpp"


void init_modbus_client();


void set_response_timeout(TimeType t);


bool read_u16_from(beef::InterfaceBase *current_screen, uint8_t slave, uint16_t address, uint16_t *dst, uint8_t count);


bool read_u32_from(beef::InterfaceBase *current_screen, uint8_t slave, uint16_t address, uint32_t *dst);


bool write_u16_to(beef::InterfaceBase *current_screen, uint8_t slave, uint16_t address, uint16_t value);


inline bool read_count(beef::InterfaceBase *current_screen, uint8_t slave, uint32_t *dst) {
    return read_u32_from(current_screen, slave, 0, dst);
}


/**
 * @brief 读取配置信息
 * 
 * 从寄存器2 开始依次读到7，分别对应：
 * 
 * 2. 设备地址
 * 3. 单测、连测、停止模式；
 * 4. 距离偏置
 * 5. 连测间隔
 * 6. 波特率
 * 7. 距离单位
 * 
 * @param current_screen 
 * @param slave 
 * @param dst             存储读取结果的缓冲区，长度至少为6
 * @return true 
 * @return false 
 */
inline bool read_config(beef::InterfaceBase *current_screen, uint8_t slave, uint16_t *dst) {
    return read_u16_from(current_screen, slave, 2, dst, 6);
}


enum class sensor_mode {
    单测 = 79,
    连测 = 67,
    停止 = 85,
};


inline bool write_mode(beef::InterfaceBase *current_screen, uint8_t slave, sensor_mode m) {
    uint16_t mm = static_cast<uint16_t>(m);
    return write_u16_to(current_screen, slave, 3, mm);
}


inline bool write_device_address(beef::InterfaceBase *current_screen, uint8_t addr) {
    return write_u16_to(current_screen, 0xf7, 2, addr);
}


inline bool read_device_address(beef::InterfaceBase *current_screen, uint16_t *addr) {
    return read_u16_from(current_screen, 0xf7, 2, addr, 1);
}